<?php
/** 
*
* @package install
* @version $Id: cf_install.php,v 1.020 2008/11/06 18:31:00 nedka Exp $
* @copyright (c) 2007, 2008 nedka (Nguyen Dang Khoa) 
* @license http://opensource.org/licenses/gpl-license.php GNU Public License 
*
*/

// Current version of Country Flags MOD
$cf_version = '2.0.0';

if (defined('IN_PHPBB') && defined('IN_INSTALL'))
{
	return;
}

/**
*/
define('IN_PHPBB', true);
define('IN_INSTALL', true);

$phpbb_root_path = './../';
$phpEx = substr(strrchr(__FILE__, '.'), 1);

// Report all errors, except notices
// error_reporting(E_ALL ^ E_NOTICE);
error_reporting(E_ALL);

@set_time_limit(0);

// Include essential scripts
include($phpbb_root_path . 'config.' . $phpEx);


// Load extensions
if (!empty($load_extensions))
{
	$load_extensions = explode(',', $load_extensions);

	foreach ($load_extensions as $extension)
	{
		@dl(trim($extension));
	}
}

// Include files
require($phpbb_root_path . 'includes/acm/acm_' . $acm_type . '.' . $phpEx);
require($phpbb_root_path . 'includes/cache.' . $phpEx);
require($phpbb_root_path . 'includes/template.' . $phpEx);
require($phpbb_root_path . 'includes/session.' . $phpEx);
require($phpbb_root_path . 'includes/auth.' . $phpEx);
require($phpbb_root_path . 'includes/functions.' . $phpEx);
require($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
require($phpbb_root_path . 'includes/constants.' . $phpEx);
require($phpbb_root_path . 'includes/db/' . $dbms . '.' . $phpEx);
require($phpbb_root_path . 'includes/utf/utf_tools.' . $phpEx);

// If we are on PHP >= 6.0.0 we do not need some code
if (version_compare(PHP_VERSION, '6.0.0-dev', '>='))
{
	/**
	* @ignore
	*/
	define('STRIP', false);
}
else
{
	set_magic_quotes_runtime(0);
	define('STRIP', (get_magic_quotes_gpc()) ? true : false);
}

$user = new user();
$cache = new cache();
$db = new $sql_db();

// Connect to DB
$db->sql_connect($dbhost, $dbuser, $dbpasswd, $dbname, $dbport, false, false);

// We do not need this any longer, unset for safety purposes
unset($dbpasswd);

$sql = "SELECT config_value
	FROM " . CONFIG_TABLE . "
	WHERE config_name = 'default_lang'";
$result = $db->sql_query($sql);
$row = $db->sql_fetchrow($result);
$db->sql_freeresult($result);

$language = basename(request_var('language', ''));

if (!$language)
{
	$language = $row['config_value'];
}

if (!file_exists($phpbb_root_path . 'language/' . $language))
{
	die('No language found!');
}

// And finally, load the relevant language files
include($phpbb_root_path . 'language/' . $language . '/common.' . $phpEx);
include($phpbb_root_path . 'language/' . $language . '/acp/common.' . $phpEx);
include($phpbb_root_path . 'language/' . $language . '/install.' . $phpEx);

// Set PHP error handler to ours
// set_error_handler('msg_handler');

// Define some variables for the database update
$inline_update = (request_var('type', 0)) ? true : false;

// Database column types mapping
$dbms_type_map = array(
	'mysql_41'	=> array(
		'INT:'			=> 'int(%d)',
		'BINT'			=> 'bigint(20)',
		'UINT'			=> 'mediumint(8) UNSIGNED',
		'UINT:'			=> 'int(%d) UNSIGNED',
		'TINT:'			=> 'tinyint(%d)',
		'USINT'			=> 'smallint(4) UNSIGNED',
		'BOOL'			=> 'tinyint(1) UNSIGNED',
		'VCHAR'			=> 'varchar(255)',
		'VCHAR:'		=> 'varchar(%d)',
		'CHAR:'			=> 'char(%d)',
		'XSTEXT'		=> 'text',
		'XSTEXT_UNI'	=> 'varchar(100)',
		'STEXT'			=> 'text',
		'STEXT_UNI'		=> 'varchar(255)',
		'TEXT'			=> 'text',
		'TEXT_UNI'		=> 'text',
		'MTEXT'			=> 'mediumtext',
		'MTEXT_UNI'		=> 'mediumtext',
		'TIMESTAMP'		=> 'int(11) UNSIGNED',
		'DECIMAL'		=> 'decimal(5,2)',
		'VCHAR_UNI'		=> 'varchar(255)',
		'VCHAR_UNI:'	=> 'varchar(%d)',
		'VCHAR_CI'		=> 'varchar(255)',
		'VARBINARY'		=> 'varbinary(255)',
	),

	'mysql_40'	=> array(
		'INT:'			=> 'int(%d)',
		'BINT'			=> 'bigint(20)',
		'UINT'			=> 'mediumint(8) UNSIGNED',
		'UINT:'			=> 'int(%d) UNSIGNED',
		'TINT:'			=> 'tinyint(%d)',
		'USINT'			=> 'smallint(4) UNSIGNED',
		'BOOL'			=> 'tinyint(1) UNSIGNED',
		'VCHAR'			=> 'varbinary(255)',
		'VCHAR:'		=> 'varbinary(%d)',
		'CHAR:'			=> 'binary(%d)',
		'XSTEXT'		=> 'blob',
		'XSTEXT_UNI'	=> 'blob',
		'STEXT'			=> 'blob',
		'STEXT_UNI'		=> 'blob',
		'TEXT'			=> 'blob',
		'TEXT_UNI'		=> 'blob',
		'MTEXT'			=> 'mediumblob',
		'MTEXT_UNI'		=> 'mediumblob',
		'TIMESTAMP'		=> 'int(11) UNSIGNED',
		'DECIMAL'		=> 'decimal(5,2)',
		'VCHAR_UNI'		=> 'blob',
		'VCHAR_UNI:'	=> array('varbinary(%d)', 'limit' => array('mult', 3, 255, 'blob')),
		'VCHAR_CI'		=> 'blob',
		'VARBINARY'		=> 'varbinary(255)',
	),

	'firebird'	=> array(
		'INT:'			=> 'INTEGER',
		'BINT'			=> 'DOUBLE PRECISION',
		'UINT'			=> 'INTEGER',
		'UINT:'			=> 'INTEGER',
		'TINT:'			=> 'INTEGER',
		'USINT'			=> 'INTEGER',
		'BOOL'			=> 'INTEGER',
		'VCHAR'			=> 'VARCHAR(255) CHARACTER SET NONE',
		'VCHAR:'		=> 'VARCHAR(%d) CHARACTER SET NONE',
		'CHAR:'			=> 'CHAR(%d) CHARACTER SET NONE',
		'XSTEXT'		=> 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
		'STEXT'			=> 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
		'TEXT'			=> 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
		'MTEXT'			=> 'BLOB SUB_TYPE TEXT CHARACTER SET NONE',
		'XSTEXT_UNI'	=> 'VARCHAR(100) CHARACTER SET UTF8',
		'STEXT_UNI'		=> 'VARCHAR(255) CHARACTER SET UTF8',
		'TEXT_UNI'		=> 'BLOB SUB_TYPE TEXT CHARACTER SET UTF8',
		'MTEXT_UNI'		=> 'BLOB SUB_TYPE TEXT CHARACTER SET UTF8',
		'TIMESTAMP'		=> 'INTEGER',
		'DECIMAL'		=> 'DOUBLE PRECISION',
		'VCHAR_UNI'		=> 'VARCHAR(255) CHARACTER SET UTF8',
		'VCHAR_UNI:'	=> 'VARCHAR(%d) CHARACTER SET UTF8',
		'VCHAR_CI'		=> 'VARCHAR(255) CHARACTER SET UTF8',
		'VARBINARY'		=> 'CHAR(255) CHARACTER SET NONE',
	),

	'mssql'		=> array(
		'INT:'			=> '[int]',
		'BINT'			=> '[float]',
		'UINT'			=> '[int]',
		'UINT:'			=> '[int]',
		'TINT:'			=> '[int]',
		'USINT'			=> '[int]',
		'BOOL'			=> '[int]',
		'VCHAR'			=> '[varchar] (255)',
		'VCHAR:'		=> '[varchar] (%d)',
		'CHAR:'			=> '[char] (%d)',
		'XSTEXT'		=> '[varchar] (1000)',
		'STEXT'			=> '[varchar] (3000)',
		'TEXT'			=> '[varchar] (8000)',
		'MTEXT'			=> '[text]',
		'XSTEXT_UNI'	=> '[varchar] (100)',
		'STEXT_UNI'		=> '[varchar] (255)',
		'TEXT_UNI'		=> '[varchar] (4000)',
		'MTEXT_UNI'		=> '[text]',
		'TIMESTAMP'		=> '[int]',
		'DECIMAL'		=> '[float]',
		'VCHAR_UNI'		=> '[varchar] (255)',
		'VCHAR_UNI:'	=> '[varchar] (%d)',
		'VCHAR_CI'		=> '[varchar] (255)',
		'VARBINARY'		=> '[varchar] (255)',
	),

	'oracle'	=> array(
		'INT:'			=> 'number(%d)',
		'BINT'			=> 'number(20)',
		'UINT'			=> 'number(8)',
		'UINT:'			=> 'number(%d)',
		'TINT:'			=> 'number(%d)',
		'USINT'			=> 'number(4)',
		'BOOL'			=> 'number(1)',
		'VCHAR'			=> 'varchar2(255)',
		'VCHAR:'		=> 'varchar2(%d)',
		'CHAR:'			=> 'char(%d)',
		'XSTEXT'		=> 'varchar2(1000)',
		'STEXT'			=> 'varchar2(3000)',
		'TEXT'			=> 'clob',
		'MTEXT'			=> 'clob',
		'XSTEXT_UNI'	=> 'varchar2(300)',
		'STEXT_UNI'		=> 'varchar2(765)',
		'TEXT_UNI'		=> 'clob',
		'MTEXT_UNI'		=> 'clob',
		'TIMESTAMP'		=> 'number(11)',
		'DECIMAL'		=> 'number(5, 2)',
		'VCHAR_UNI'		=> 'varchar2(765)',
		'VCHAR_UNI:'	=> array('varchar2(%d)', 'limit' => array('mult', 3, 765, 'clob')),
		'VCHAR_CI'		=> 'varchar2(255)',
		'VARBINARY'		=> 'raw(255)',
	),

	'sqlite'	=> array(
		'INT:'			=> 'int(%d)',
		'BINT'			=> 'bigint(20)',
		'UINT'			=> 'INTEGER UNSIGNED', // 'mediumint(8) UNSIGNED',
		'UINT:'			=> 'INTEGER UNSIGNED', // 'int(%d) UNSIGNED',
		'TINT:'			=> 'tinyint(%d)',
		'USINT'			=> 'INTEGER UNSIGNED', // 'mediumint(4) UNSIGNED',
		'BOOL'			=> 'INTEGER UNSIGNED', // 'tinyint(1) UNSIGNED',
		'VCHAR'			=> 'varchar(255)',
		'VCHAR:'		=> 'varchar(%d)',
		'CHAR:'			=> 'char(%d)',
		'XSTEXT'		=> 'text(65535)',
		'STEXT'			=> 'text(65535)',
		'TEXT'			=> 'text(65535)',
		'MTEXT'			=> 'mediumtext(16777215)',
		'XSTEXT_UNI'	=> 'text(65535)',
		'STEXT_UNI'		=> 'text(65535)',
		'TEXT_UNI'		=> 'text(65535)',
		'MTEXT_UNI'		=> 'mediumtext(16777215)',
		'TIMESTAMP'		=> 'INTEGER UNSIGNED', // 'int(11) UNSIGNED',
		'DECIMAL'		=> 'decimal(5,2)',
		'VCHAR_UNI'		=> 'varchar(255)',
		'VCHAR_UNI:'	=> 'varchar(%d)',
		'VCHAR_CI'		=> 'varchar(255)',
		'VARBINARY'		=> 'blob',
	),

	'postgres'	=> array(
		'INT:'			=> 'INT4',
		'BINT'			=> 'INT8',
		'UINT'			=> 'INT4', // UNSIGNED
		'UINT:'			=> 'INT4', // UNSIGNED
		'USINT'			=> 'INT2', // UNSIGNED
		'BOOL'			=> 'INT2', // UNSIGNED
		'TINT:'			=> 'INT2',
		'VCHAR'			=> 'varchar(255)',
		'VCHAR:'		=> 'varchar(%d)',
		'CHAR:'			=> 'char(%d)',
		'XSTEXT'		=> 'varchar(1000)',
		'STEXT'			=> 'varchar(3000)',
		'TEXT'			=> 'varchar(8000)',
		'MTEXT'			=> 'TEXT',
		'XSTEXT_UNI'	=> 'varchar(100)',
		'STEXT_UNI'		=> 'varchar(255)',
		'TEXT_UNI'		=> 'varchar(4000)',
		'MTEXT_UNI'		=> 'TEXT',
		'TIMESTAMP'		=> 'INT4', // UNSIGNED
		'DECIMAL'		=> 'decimal(5,2)',
		'VCHAR_UNI'		=> 'varchar(255)',
		'VCHAR_UNI:'	=> 'varchar(%d)',
		'VCHAR_CI'		=> 'varchar_ci',
		'VARBINARY'		=> 'bytea',
	),
);

// A list of types being unsigned for better reference in some DB's
$unsigned_types = array('UINT', 'UINT:', 'USINT', 'BOOL', 'TIMESTAMP');

// Determine mapping database type
switch ($db->sql_layer)
{
	case 'mysql':
		$map_dbms = 'mysql_40';
	break;

	case 'mysql4':
		if (version_compare($db->mysql_version, '4.1.3', '>='))
		{
			$map_dbms = 'mysql_41';
		}
		else
		{
			$map_dbms = 'mysql_40';
		}
	break;

	case 'mysqli':
		$map_dbms = 'mysql_41';
	break;

	case 'mssql':
	case 'mssql_odbc':
		$map_dbms = 'mssql';
	break;

	default:
		$map_dbms = $db->sql_layer;
	break;
}

// Create new table: "_flags"
// Yeah, this installer supported all database types which bb4dd supported :D
switch ($map_dbms)
{
	case 'firebird':
		$sql = "CREATE TABLE {$table_prefix}flags (
					flag_id INTEGER NOT NULL,
					flag_country VARCHAR(255) CHARACTER SET UTF8 DEFAULT '' NOT NULL COLLATE UNICODE,
					flag_code VARCHAR(2) CHARACTER SET UTF8 DEFAULT '' NOT NULL COLLATE UNICODE,
					flag_image VARCHAR(255) CHARACTER SET NONE DEFAULT '' NOT NULL
				);;
				ALTER TABLE {$table_prefix}flags ADD PRIMARY KEY (flag_id);;";
	break;

	case 'mssql':
		$sql = "CREATE TABLE [{$table_prefix}flags] (
					[flag_id] [int] IDENTITY (1, 1) NOT NULL ,
					[flag_country] [varchar] (255) DEFAULT ('') NOT NULL ,
					[flag_code] [varchar] (2) DEFAULT ('') NOT NULL ,
					[flag_image] [varchar] (255) DEFAULT ('') NOT NULL 
				) ON [PRIMARY]
				GO
				ALTER TABLE [{$table_prefix}flags] WITH NOCHECK ADD 
					CONSTRAINT [PK_{$table_prefix}flags] PRIMARY KEY  CLUSTERED 
					(
						[flag_id]
					)  ON [PRIMARY] 
				GO";
	break;

	case 'mysql_40':
		$sql = "CREATE TABLE {$table_prefix}flags (
					flag_id mediumint(8) UNSIGNED NOT NULL auto_increment,
					flag_country blob NOT NULL,
					flag_code blob NOT NULL,
					flag_image varbinary(255) DEFAULT '' NOT NULL,
					PRIMARY KEY (flag_id)
				);";
	break;

	case 'mysql_41':
		$sql = "CREATE TABLE {$table_prefix}flags (
					flag_id mediumint(8) UNSIGNED NOT NULL auto_increment,
					flag_country varchar(255) DEFAULT '' NOT NULL,
					flag_code varchar(2) DEFAULT '' NOT NULL,
					flag_image varchar(255) DEFAULT '' NOT NULL,
					PRIMARY KEY (flag_id)
				) CHARACTER SET `utf8` COLLATE `utf8_bin`;";
	break;

	case 'oracle':
		$sql = "CREATE TABLE {$table_prefix}flags (
					flag_id number(8) NOT NULL,
					flag_country varchar2(765) DEFAULT '' ,
					flag_code varchar2(765) DEFAULT '' ,
					flag_image varchar2(255) DEFAULT '' ,
					CONSTRAINT pk_{$table_prefix}flags PRIMARY KEY (flag_id)
				)
				/
				CREATE SEQUENCE {$table_prefix}flags_seq
				/
				CREATE OR REPLACE TRIGGER t_{$table_prefix}flags
				BEFORE INSERT ON {$table_prefix}flags
				FOR EACH ROW WHEN (
					new.flag_id IS NULL OR new.flag_id = 0
				)
				BEGIN
					SELECT {$table_prefix}flags_seq.nextval
					INTO :new.flag_id
					FROM dual;
				END;
				/";
	break;

	case 'postgres':
		$sql = "CREATE SEQUENCE {$table_prefix}flags_seq;
				CREATE TABLE {$table_prefix}flags (
					flag_id INT4 DEFAULT nextval({$table_prefix}flags_seq),
					flag_country varchar(255) DEFAULT '' NOT NULL,
					flag_code varchar(2) DEFAULT '' NOT NULL,
					flag_image varchar(255) DEFAULT '' NOT NULL,
					PRIMARY KEY (flag_id)
				);";
	break;

	case 'sqlite':
		$sql = "CREATE TABLE {$table_prefix}flags (
					flag_id INTEGER PRIMARY KEY NOT NULL ,
					flag_country varchar(255) NOT NULL DEFAULT '',
					flag_code varchar(2) NOT NULL DEFAULT '',
					flag_image varchar(255) NOT NULL DEFAULT '',
					PRIMARY KEY (flag_id)
				);";
	break;
}
$db->sql_query($sql);

// Only an example, but also commented out
$database_update_info = array(
	// Changes from bb4dd 1 original to the latest version of this MOD
	// I set '0.1.0' below as first version of this MOD :)
	'0.1.0'			=> array(
		// Add the following columns
		'add_columns'		=> array(
			USERS_TABLE			=> array(
				'user_flag'				=> array('VCHAR:30', ''),
			),
			GROUPS_TABLE		=> array(
				'group_flag'			=> array('VCHAR:30', ''),
			),
		),
	),
);

// Determine mapping database type
switch ($db->sql_layer)
{
	case 'mysql':
		$map_dbms = 'mysql_40';
	break;

	case 'mysql4':
		if (version_compare($db->mysql_version, '4.1.3', '>='))
		{
			$map_dbms = 'mysql_41';
		}
		else
		{
			$map_dbms = 'mysql_40';
		}
	break;

	case 'mysqli':
		$map_dbms = 'mysql_41';
	break;

	case 'mssql':
	case 'mssql_odbc':
		$map_dbms = 'mssql';
	break;

	default:
		$map_dbms = $db->sql_layer;
	break;
}

$error_ary = array();
$errored = false;


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="<?php echo $lang['DIRECTION']; ?>" lang="<?php echo $lang['USER_LANG']; ?>" xml:lang="<?php echo $lang['USER_LANG']; ?>">
<head>

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="content-language" content="<?php echo $lang['USER_LANG']; ?>" />
<meta http-equiv="content-style-type" content="text/css" />
<meta http-equiv="imagetoolbar" content="no" />

<title><?php echo $lang['UPDATING_TO_LATEST_STABLE']; ?></title>

<link href="../adm/style/admin.css" rel="stylesheet" type="text/css" media="screen" />

</head>

<body>
<div id="wrap">
	<div id="page-header">&nbsp;</div>

	<div id="page-body">
		<div id="acp">
			<div class="panel">
				<span class="corners-top"><span></span></span>
					<div id="content">
						<div id="main">

<h1><?php echo 'Updating database for this MOD'; ?></h1>
<br />
<p><?php echo $lang['DATABASE_TYPE']; ?>: <strong><?php echo $db->sql_layer; ?></strong><br />

<?php

// To let set_config() calls succeed, we need to make the config array available globally
$config = array();
$sql = 'SELECT *
	FROM ' . CONFIG_TABLE;
$result = $db->sql_query($sql);

while ($row = $db->sql_fetchrow($result))
{
	$config[$row['config_name']] = $row['config_value'];
}
$db->sql_freeresult($result);

echo 'Your bb4dd version is <strong>' . $config['version'] . '</strong><br />';
echo 'You are installing Country Flags MOD version <strong>' . $cf_version . '</strong> [Database Part]';

// Schema updates
?>

</p><br /><br />
<h1><?php echo $lang['UPDATE_DATABASE_SCHEMA']; ?></h1>
<br />
<p><?php echo $lang['PROGRESS']; ?> :: <strong>

<?php

flush();

// We go through the schema changes from the lowest to the highest version
// We skip those versions older than the current version
$no_updates = true;
foreach ($database_update_info as $version => $schema_changes)
{
	if (!sizeof($schema_changes))
	{
		continue;
	}

	$no_updates = false;

	// Change columns?
	if (!empty($schema_changes['change_columns']))
	{
		foreach ($schema_changes['change_columns'] as $table => $columns)
		{
			foreach ($columns as $column_name => $column_data)
			{
				sql_column_change($map_dbms, $table, $column_name, $column_data);
			}
		}
	}

	// Add columns?
	if (!empty($schema_changes['add_columns']))
	{
		foreach ($schema_changes['add_columns'] as $table => $columns)
		{
			foreach ($columns as $column_name => $column_data)
			{
				// Only add the column if it does not exist yet
				if (!column_exists($map_dbms, $table, $column_name))
				{
					sql_column_add($map_dbms, $table, $column_name, $column_data);
				}
			}
		}
	}
}

_write_result($no_updates, $errored, $error_ary);

// Data updates
$error_ary = array();
$errored = $no_updates = false;

?>

<br /><br />
<h1><?php echo $lang['UPDATING_DATA']; ?></h1>
<br />
<p><?php echo $lang['PROGRESS']; ?> :: <strong>

<?php

flush();

$no_updates = true;

// Some code magic

// Define table
define('FLAGS_TABLE', $table_prefix . 'flags');

// Add the new permissions: a_flags
// Used for acp_flags module mode
$sql_ary = array(
	'auth_option'		=> 'a_flags',
	'is_global'			=> 1,
	'is_local'			=> 0,
	'founder_only'		=> 0,
);
$db->sql_query('INSERT INTO ' . ACL_OPTIONS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));

// Add config variables
set_config('flags_path', 'images/flags');
set_config('require_flag', '1');
set_config('default_flag', '');

// Insert data for country flags
add_flags();

$no_updates = false;

_write_result($no_updates, $errored, $error_ary);

$error_ary = array();
$errored = $no_updates = false;

?>

<br /><br />
<h1><?php echo $lang['UPDATE_VERSION_OPTIMIZE']; ?></h1>
<br />
<p><?php echo $lang['PROGRESS']; ?> :: <strong>

<?php

flush();

// Optimize/vacuum analyze the tables where appropriate
// Below is the list of all tables in phpBB3 + "_flags" table is added above
switch ($db->sql_layer)
{
	case 'mysql':
	case 'mysqli':
	case 'mysql4':
		$sql = "OPTIMIZE TABLE
			{$table_prefix}acl_groups,
			{$table_prefix}acl_options,
			{$table_prefix}acl_roles_data,
			{$table_prefix}acl_roles,
			{$table_prefix}acl_users,
			{$table_prefix}attachments,
			{$table_prefix}banlist,
			{$table_prefix}bbcodes,
			{$table_prefix}bookmarks,
			{$table_prefix}bots,
			{$table_prefix}config,
			{$table_prefix}confirm,
			{$table_prefix}disallow,
			{$table_prefix}drafts,
			{$table_prefix}extensions,
			{$table_prefix}extension_groups,
			{$table_prefix}flags,
			{$table_prefix}forums,
			{$table_prefix}forums_access,
			{$table_prefix}forums_track,
			{$table_prefix}forums_watch,
			{$table_prefix}groups,
			{$table_prefix}icons,
			{$table_prefix}lang,
			{$table_prefix}log,
			{$table_prefix}moderator_cache,
			{$table_prefix}modules,
			{$table_prefix}poll_options,
			{$table_prefix}poll_votes,
			{$table_prefix}posts,
			{$table_prefix}privmsgs,
			{$table_prefix}privmsgs_folder,
			{$table_prefix}privmsgs_rules,
			{$table_prefix}privmsgs_to,
			{$table_prefix}profile_fields,
			{$table_prefix}profile_fields_data,
			{$table_prefix}profile_fields_lang,
			{$table_prefix}profile_lang,
			{$table_prefix}ranks,
			{$table_prefix}reports,
			{$table_prefix}reports_reasons,
			{$table_prefix}search_results,
			{$table_prefix}search_wordlist,
			{$table_prefix}search_wordmatch,
			{$table_prefix}sessions,
			{$table_prefix}sessions_keys,
			{$table_prefix}sitelist,
			{$table_prefix}smilies,
			{$table_prefix}styles,
			{$table_prefix}styles_imageset,
			{$table_prefix}styles_imageset_data,
			{$table_prefix}styles_template,
			{$table_prefix}styles_template_data,
			{$table_prefix}styles_theme,
			{$table_prefix}topics,
			{$table_prefix}topics_posted,
			{$table_prefix}topics_track,
			{$table_prefix}topics_watch,
			{$table_prefix}user_group,
			{$table_prefix}users,
			{$table_prefix}warnings,
			{$table_prefix}words,
			{$table_prefix}zebra";
		_sql($sql, $errored, $error_ary);
	break;

	case 'postgresql':
		_sql("VACUUM ANALYZE", $errored, $error_ary);
	break;
}

_write_result($no_updates, $errored, $error_ary);


?>

<br />
<h1><?php echo 'تم تركيب الاضافة بنجاح الآن عد الى الصفحة السابقة واضغط الانتقال الى الصفحة التالية'; ?></h1>
<br />

<?php
// Add database update to log
$user->ip = (!empty($_SERVER['REMOTE_ADDR'])) ? htmlspecialchars($_SERVER['REMOTE_ADDR']) : '';
add_log('admin', 'Installed Country Flags MOD ' . $cf_version . ' successfully.');

// Now we purge the session table as well as all cache files
$cache->purge();

?>

						</div>
					</div>
				<span class="corners-bottom"><span></span></span>
			</div>
		</div>
	</div>
	
	<div id="page-footer">
		Country Flags &copy; 2009 by <a href="http://www.bb4dd.com/">bb4dd Group</a>
	</div>
</div>

</body>
</html>

<?php

/**
* Function for triggering an sql statement
*/
function _sql($sql, &$errored, &$error_ary, $echo_dot = true)
{
	global $db;

	if (defined('DEBUG_EXTRA'))
	{
		echo "<br />\n{$sql}\n<br />";
	}

	$db->sql_return_on_error(true);

	$result = $db->sql_query($sql);

	if ($db->sql_error_triggered)
	{
		$errored = true;
		$error_ary['sql'][] = $db->sql_error_sql;
		$error_ary['error_code'][] = $db->_sql_error();
	}

	$db->sql_return_on_error(false);

	if ($echo_dot)
	{
		echo ". \n";
		flush();
	}

	return $result;
}

function _write_result($no_updates, $errored, $error_ary)
{
	global $lang;

	if ($no_updates)
	{
		echo ' ' . $lang['NO_UPDATES_REQUIRED'] . '</strong></p>';
	}
	else
	{
		echo ' <span class="success">' . $lang['DONE'] . '</span></strong><br />' . $lang['RESULT'] . ' :: ';

		if ($errored)
		{
			echo ' <strong>' . $lang['SOME_QUERIES_FAILED'] . '</strong> <ul>';

			for ($i = 0; $i < sizeof($error_ary['sql']); $i++)
			{
				echo '<li>' . $lang['ERROR'] . ' :: <strong>' . $error_ary['error_code'][$i]['message'] . '</strong><br />';
				echo $lang['SQL'] . ' :: <strong>' . $error_ary['sql'][$i] . '</strong><br /><br /></li>';
			}

			echo '</ul> <br /><br />' . $lang['SQL_FAILURE_EXPLAIN'] . '</p>';
		}
		else
		{
			echo '<strong>' . $lang['NO_ERRORS'] . '</strong></p>';
		}
	}
}

/**
* Check if a specified column exist
*/
function column_exists($dbms, $table, $column_name)
{
	global $db;

	$db->sql_return_on_error(true);

	$sql = "SELECT $column_name FROM $table";
	$result = $db->sql_query_limit($sql, 1);
	$row = $db->sql_fetchrow($result);
	$db->sql_freeresult($result);

	$error = ($db->sql_error_triggered) ? true : false;

	$db->sql_return_on_error(false);

	return (!$error) ? true : false;
}

/**
* Function to prepare some column information for better usage
*/
function prepare_column_data($dbms, $column_data)
{
	global $dbms_type_map, $unsigned_types;

	// Get type
	if (strpos($column_data[0], ':') !== false)
	{
		list($orig_column_type, $column_length) = explode(':', $column_data[0]);

		if (!is_array($dbms_type_map[$dbms][$orig_column_type . ':']))
		{
			$column_type = sprintf($dbms_type_map[$dbms][$orig_column_type . ':'], $column_length);
		}
		else
		{
			if (isset($dbms_type_map[$dbms][$orig_column_type . ':']['rule']))
			{
				switch ($dbms_type_map[$dbms][$orig_column_type . ':']['rule'][0])
				{
					case 'div':
						$column_length /= $dbms_type_map[$dbms][$orig_column_type . ':']['rule'][1];
						$column_length = ceil($column_length);
						$column_type = sprintf($dbms_type_map[$dbms][$orig_column_type . ':'][0], $column_length);
					break;
				}
			}

			if (isset($dbms_type_map[$dbms][$orig_column_type . ':']['limit']))
			{
				switch ($dbms_type_map[$dbms][$orig_column_type . ':']['limit'][0])
				{
					case 'mult':
						$column_length *= $dbms_type_map[$dbms][$orig_column_type . ':']['limit'][1];
						if ($column_length > $dbms_type_map[$dbms][$orig_column_type . ':']['limit'][2])
						{
							$column_type = $dbms_type_map[$dbms][$orig_column_type . ':']['limit'][3];
						}
						else
						{
							$column_type = sprintf($dbms_type_map[$dbms][$orig_column_type . ':'][0], $column_length);
						}
					break;
				}
			}
		}
		$orig_column_type .= ':';
	}
	else
	{
		$orig_column_type = $column_data[0];
		$column_type = $dbms_type_map[$dbms][$column_data[0]];
	}

	// Adjust default value if db-dependant specified
	if (is_array($column_data[1]))
	{
		$column_data[1] = (isset($column_data[1][$dbms])) ? $column_data[1][$dbms] : $column_data[1]['default'];
	}

	$sql = '';

	switch ($dbms)
	{
		case 'firebird':
			$sql .= " {$column_type} ";

			if (!is_null($column_data[1]))
			{
				$sql .= 'DEFAULT ' . ((is_numeric($column_data[1])) ? $column_data[1] : "'{$column_data[1]}'") . ' ';
			}

			$sql .= 'NOT NULL';

			// This is a UNICODE column and thus should be given it's fair share
			if (preg_match('/^X?STEXT_UNI|VCHAR_(CI|UNI:?)/', $column_data[0]))
			{
				$sql .= ' COLLATE UNICODE';
			}

		break;

		case 'mssql':
			$sql .= " {$column_type} ";

			if (!is_null($column_data[1]))
			{
				// For hexadecimal values do not use single quotes
				if (strpos($column_data[1], '0x') === 0)
				{
					$sql .= 'DEFAULT (' . $column_data[1] . ') ';
				}
				else
				{
					$sql .= 'DEFAULT (' . ((is_numeric($column_data[1])) ? $column_data[1] : "'{$column_data[1]}'") . ') ';
				}
			}

			$sql .= 'NOT NULL';
		break;

		case 'mysql_40':
		case 'mysql_41':
			$sql .= " {$column_type} ";

			// For hexadecimal values do not use single quotes
			if (!is_null($column_data[1]) && substr($column_type, -4) !== 'text' && substr($column_type, -4) !== 'blob')
			{
				$sql .= (strpos($column_data[1], '0x') === 0) ? "DEFAULT {$column_data[1]} " : "DEFAULT '{$column_data[1]}' ";
			}
			$sql .= 'NOT NULL';

			if (isset($column_data[2]))
			{
				if ($column_data[2] == 'auto_increment')
				{
					$sql .= ' auto_increment';
				}
				else if ($dbms === 'mysql_41' && $column_data[2] == 'true_sort')
				{
					$sql .= ' COLLATE utf8_unicode_ci';
				}
			}

		break;

		case 'oracle':
			$sql .= " {$column_type} ";
			$sql .= (!is_null($column_data[1])) ? "DEFAULT '{$column_data[1]}' " : '';

			// In Oracle empty strings ('') are treated as NULL.
			// Therefore in Oracle we allow NULL's for all DEFAULT '' entries
			$sql .= ($column_data[1] === '') ? '' : 'NOT NULL';
		break;

		case 'postgres':
			$sql .= " {$column_type} ";

			$sql .= (!is_null($column_data[1])) ? "DEFAULT '{$column_data[1]}' " : '';
			$sql .= 'NOT NULL';

			// Unsigned? Then add a CHECK contraint
			if (in_array($orig_column_type, $unsigned_types))
			{
				$sql .= " CHECK ({$column_name} >= 0)";
			}
		break;

		case 'sqlite':
/*			if (isset($column_data[2]) && $column_data[2] == 'auto_increment')
			{
				$sql .= ' INTEGER PRIMARY KEY';
			}
			else
			{
				$sql .= ' ' . $column_type;
			}
*/
			$sql .= ' ' . $column_type;

			$sql .= ' NOT NULL ';
			$sql .= (!is_null($column_data[1])) ? "DEFAULT '{$column_data[1]}'" : '';
		break;
	}

	return array(
		'column_type_sql'		=> $sql,
	);
}

/**
* Add new column
*/
function sql_column_add($dbms, $table_name, $column_name, $column_data)
{
	global $errored, $error_ary;

	$column_data = prepare_column_data($dbms, $column_data);

	switch ($dbms)
	{
		case 'firebird':
			$sql = 'ALTER TABLE "' . $table_name . '" ADD "' . $column_name . '" ' . $column_data['column_type_sql'];
			_sql($sql, $errored, $error_ary);
		break;

		case 'mssql':
			$sql = 'ALTER TABLE [' . $table_name . '] ADD [' . $column_name . '] ' . $column_data['column_type_sql'];
			_sql($sql, $errored, $error_ary);
		break;

		case 'mysql_40':
		case 'mysql_41':
			$sql = 'ALTER TABLE `' . $table_name . '` ADD COLUMN `' . $column_name . '` ' . $column_data['column_type_sql'];
			_sql($sql, $errored, $error_ary);
		break;

		case 'oracle':
			$sql = 'ALTER TABLE ' . $table_name . ' ADD ' . $column_name . ' ' . $column_data['column_type_sql'];
			_sql($sql, $errored, $error_ary);
		break;

		case 'postgres':
			$sql = 'ALTER TABLE ' . $table_name . ' ADD COLUMN "' . $column_name . '" ' . $column_data['column_type_sql'];
			_sql($sql, $errored, $error_ary);
		break;

		case 'sqlite':
			if (version_compare(sqlite_libversion(), '3.0') == -1)
			{
				global $db;
				$sql = "SELECT sql
					FROM sqlite_master 
					WHERE type = 'table' 
						AND name = '{$table_name}'
					ORDER BY type DESC, name;";
				$result = $db->sql_query($sql);

				if (!$result)
				{
					break;
				}

				$row = $db->sql_fetchrow($result);
				$db->sql_freeresult($result);

				$db->sql_transaction('begin');

				// Create a backup table and populate it, destroy the existing one
				$db->sql_query(preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']));
				$db->sql_query('INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name);
				$db->sql_query('DROP TABLE ' . $table_name);

				preg_match('#\((.*)\)#s', $row['sql'], $matches);

				$new_table_cols = trim($matches[1]);
				$old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols);
				$column_list = array();

				foreach ($old_table_cols as $declaration)
				{
					$entities = preg_split('#\s+#', trim($declaration));
					if ($entities[0] == 'PRIMARY')
					{
						continue;
					}
					$column_list[] = $entities[0];
				}

				$columns = implode(',', $column_list);

				$new_table_cols = $column_name . ' ' . $column_data['column_type_sql'] . ',' . $new_table_cols;

				// Create a new table and fill it up. destroy the temp one
				$db->sql_query('CREATE TABLE ' . $table_name . ' (' . $new_table_cols . ');');
				$db->sql_query('INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;');
				$db->sql_query('DROP TABLE ' . $table_name . '_temp');

				$db->sql_transaction('commit');
			}
			else
			{
				$sql = 'ALTER TABLE ' . $table_name . ' ADD ' . $column_name . ' [' . $column_data['column_type_sql'] . ']';
				_sql($sql, $errored, $error_ary);
			}
		break;
	}
}

/**
* Change column type (not name!)
*/
function sql_column_change($dbms, $table_name, $column_name, $column_data)
{
	global $dbms_type_map, $db;
	global $errored, $error_ary;

	$column_data = prepare_column_data($dbms, $column_data);

	switch ($dbms)
	{
		case 'firebird':
			// Change type...
			$sql = 'ALTER TABLE "' . $table_name . '" ALTER COLUMN "' . $column_name . '" TYPE ' . ' ' . $column_data['column_type_sql'];
			_sql($sql, $errored, $error_ary);
		break;

		case 'mssql':
			$sql = 'ALTER TABLE [' . $table_name . '] ALTER COLUMN [' . $column_name . '] ' . $column_data['column_type_sql'];
			_sql($sql, $errored, $error_ary);
		break;

		case 'mysql_40':
		case 'mysql_41':
			$sql = 'ALTER TABLE `' . $table_name . '` CHANGE `' . $column_name . '` `' . $column_name . '` ' . $column_data['column_type_sql'];
			_sql($sql, $errored, $error_ary);
		break;

		case 'oracle':
			$sql = 'ALTER TABLE ' . $table_name . ' MODIFY ' . $column_name . ' ' . $column_data['column_type_sql'];
			_sql($sql, $errored, $error_ary);
		break;

		case 'postgres':
			$sql = 'ALTER TABLE ' . $table_name . ' ALTER COLUMN ' . $column_name . ' SET ' . $column_data['column_type_sql'];
			_sql($sql, $errored, $error_ary);
		break;

		case 'sqlite':

			$sql = "SELECT sql
				FROM sqlite_master 
				WHERE type = 'table' 
					AND name = '{$table_name}'
				ORDER BY type DESC, name;";
			$result = _sql($sql, $errored, $error_ary);

			if (!$result)
			{
				break;
			}

			$row = $db->sql_fetchrow($result);
			$db->sql_freeresult($result);

			$db->sql_transaction('begin');

			// Create a temp table and populate it, destroy the existing one
			$db->sql_query(preg_replace('#CREATE\s+TABLE\s+"?' . $table_name . '"?#i', 'CREATE TEMPORARY TABLE ' . $table_name . '_temp', $row['sql']));
			$db->sql_query('INSERT INTO ' . $table_name . '_temp SELECT * FROM ' . $table_name);
			$db->sql_query('DROP TABLE ' . $table_name);

			preg_match('#\((.*)\)#s', $row['sql'], $matches);

			$new_table_cols = trim($matches[1]);
			$old_table_cols = preg_split('/,(?![\s\w]+\))/m', $new_table_cols);
			$column_list = array();

			foreach ($old_table_cols as $key => $declaration)
			{
				$entities = preg_split('#\s+#', trim($declaration));
				$column_list[] = $entities[0];
				if ($entities[0] == $column_name)
				{
					$old_table_cols[$key] = $column_name . ' ' . $column_data['column_type_sql'];
				}
			}

			$columns = implode(',', $column_list);

			// create a new table and fill it up. destroy the temp one
			$db->sql_query('CREATE TABLE ' . $table_name . ' (' . implode(',', $old_table_cols) . ');');
			$db->sql_query('INSERT INTO ' . $table_name . ' (' . $columns . ') SELECT ' . $columns . ' FROM ' . $table_name . '_temp;');
			$db->sql_query('DROP TABLE ' . $table_name . '_temp');

			$db->sql_transaction('commit');

		break;
	}
}

/**
* Add country flags with country name, country code and country flag images to the database
* Updated: 245 countries
* @ignore
*/
function add_flags()
{
	global $db, $errored, $error_ary;

	$flag_list = array(
		'Afghanistan'										=> array('af', 'af.png'),
		'Aland Islands'										=> array('ax', 'ax.png'),
		'Albania'											=> array('al', 'al.png'),
		'Algeria'											=> array('dz', 'dz.png'),
		'American Samoa'									=> array('as', 'as.png'),
		'Andorra'											=> array('ad', 'ad.png'),
		'Angola'											=> array('ao', 'ao.png'),
		'Anguilla'											=> array('ai', 'ai.png'),
		'Antarctica'										=> array('aq', 'aq.png'),
		'Antigua and Barbuda'								=> array('ag', 'ag.png'),
		'Argentina'											=> array('ar', 'ar.png'),
		'Armenia'											=> array('am', 'am.png'),
		'Aruba'												=> array('aw', 'aw.png'),
		'Ascension Island'									=> array('ac', 'ac.png'),
		'Australia'											=> array('au', 'au.png'),
		'Austria'											=> array('at', 'at.png'),
		'Azerbaijan'										=> array('az', 'az.png'),
		'Bahamas'											=> array('bs', 'bs.png'),
		'Bahrain'											=> array('bh', 'bh.png'),
		'Bangladesh'										=> array('bd', 'bd.png'),
		'Barbados'											=> array('bb', 'bb.png'),
		'Belarus'											=> array('by', 'by.png'),
		'Belgium'											=> array('be', 'be.png'),
		'Belize'											=> array('bz', 'bz.png'),
		'Benin'												=> array('bj', 'bj.png'),
		'Bermuda'											=> array('bm', 'bm.png'),
		'Bhutan'											=> array('bt', 'bt.png'),
		'Bolivia'											=> array('bo', 'bo.png'),
		'Bosnia and Herzegowina'							=> array('ba', 'ba.png'),
		'Botswana'											=> array('bw', 'bw.png'),
		'Bouvet Island'										=> array('bv', 'bv.png'),
		'Brazil'											=> array('br', 'br.png'),
		'British Indian Ocean Territory'					=> array('io', 'io.png'),
		'Brunei'											=> array('bn', 'bn.png'),
		'Bulgaria'											=> array('bg', 'bg.png'),
		'Burkina Faso'										=> array('bf', 'bf.png'),
		'Burundi'											=> array('bi', 'bi.png'),
		'Cambodia'											=> array('kh', 'kh.png'),
		'Cameroon'											=> array('cm', 'cm.png'),
		'Canada'											=> array('ca', 'ca.png'),
		'Cape Verde'										=> array('cv', 'cv.png'),
		'Cayman Islands'									=> array('ky', 'ky.png'),
		'Central African Republic'							=> array('cf', 'cf.png'),
		'Chad'												=> array('td', 'td.png'),
		'Chile'												=> array('cl', 'cl.png'),
		'China'												=> array('cn', 'cn.png'),
		'Christmas Island'									=> array('cx', 'cx.png'),
		'Cocos (Keeling) Islands'							=> array('cc', 'cc.png'),
		'Colombia'											=> array('co', 'co.png'),
		'Comoros'											=> array('km', 'km.png'),
		'Congo'												=> array('cg', 'cg.png'),
		'Congo, Democratic Republic of'						=> array('cd', 'cd.png'),
		'Cook Islands'										=> array('ck', 'ck.png'),
		'Costa Rica'										=> array('cr', 'cr.png'),
		'Cote d\'Ivoire'									=> array('ci', 'ci.png'),
		'Croatia'											=> array('hr', 'hr.png'),
		'Cuba'												=> array('cu', 'cu.png'),
		'Cyprus'											=> array('cy', 'cy.png'),
		'Czech Republic'									=> array('cz', 'cz.png'),
		'Denmark'											=> array('dk', 'dk.png'),
		'Djibouti'											=> array('dj', 'dj.png'),
		'Dominica'											=> array('dm', 'dm.png'),
		'Dominican Republic'								=> array('do', 'do.png'),
		'Ecuador'											=> array('ec', 'ec.png'),
		'Egypt'												=> array('eg', 'eg.png'),
		'El Salvador'										=> array('sv', 'sv.png'),
		'Equatorial Guinea'									=> array('gq', 'gq.png'),
		'Eritrea'											=> array('er', 'er.png'),
		'Estonia'											=> array('ee', 'ee.png'),
		'Ethiopia'											=> array('et', 'et.png'),
		'Falkland Islands'									=> array('fk', 'fk.png'),
		'Faroe Islands'										=> array('fo', 'fo.png'),
		'Fiji'												=> array('fj', 'fj.png'),
		'Finland'											=> array('fi', 'fi.png'),
		'France'											=> array('fr', 'fr.png'),
		'French Guiana'										=> array('gf', 'gf.png'),
		'French Polynesia'									=> array('pf', 'pf.png'),
		'French Southern Territories'						=> array('tf', 'tf.png'),
		'Gabon'												=> array('ga', 'ga.png'),
		'Gambia'											=> array('gm', 'gm.png'),
		'Georgia'											=> array('ge', 'ge.png'),
		'Germany'											=> array('de', 'de.png'),
		'Ghana'												=> array('gh', 'gh.png'),
		'Gibraltar'											=> array('gi', 'gi.png'),
		'Greece'											=> array('gr', 'gr.png'),
		'Greenland'											=> array('gl', 'gl.png'),
		'Grenada'											=> array('gd', 'gd.png'),
		'Guadeloupe'										=> array('gp', 'gp.png'),
		'Guam'												=> array('gu', 'gu.png'),
		'Guatemala'											=> array('gt', 'gt.png'),
		'Guernsey'											=> array('gg', 'gg.png'),
		'Guinea'											=> array('gn', 'gn.png'),
		'Guinea-Bissau'										=> array('gw', 'gw.png'),
		'Guyana'											=> array('gy', 'gy.png'),
		'Haiti'												=> array('ht', 'ht.png'),
		'Heard Island and McDonald Islands'					=> array('hm', 'hm.png'),
		'Holy See (Vatican City State)'						=> array('va', 'va.png'),
		'Honduras'											=> array('hn', 'hn.png'),
		'Hong Kong'											=> array('hk', 'hk.png'),
		'Hungary'											=> array('hu', 'hu.png'),
		'Iceland'											=> array('is', 'is.png'),
		'India'												=> array('in', 'in.png'),
		'Indonesia'											=> array('id', 'id.png'),
		'Iran'												=> array('ir', 'ir.png'),
		'Iraq'												=> array('iq', 'iq.png'),
		'Ireland'											=> array('ie', 'ie.png'),
		'Isle of Man'										=> array('im', 'im.png'),
		'Israel'											=> array('il', 'il.png'),
		'Italy'												=> array('it', 'it.png'),
		'Jamaica'											=> array('jm', 'jm.png'),
		'Japan'												=> array('jp', 'jp.png'),
		'Jersey'											=> array('je', 'je.png'),
		'Jordan'											=> array('jo', 'jo.png'),
		'Kazakhstan'										=> array('kz', 'kz.png'),
		'Kenya'												=> array('ke', 'ke.png'),
		'Kiribati'											=> array('ki', 'ki.png'),
		'Korea, Democratic People\'s Republic of'			=> array('kp', 'kp.png'),
		'Korea, Republic of'								=> array('kr', 'kr.png'),
		'Kuwait'											=> array('kw', 'kw.png'),
		'Kyrgyzstan'										=> array('kg', 'kg.png'),
		'Laos'												=> array('la', 'la.png'),
		'Latvia'											=> array('lv', 'lv.png'),
		'Lebanon'											=> array('lb', 'lb.png'),
		'Lesotho'											=> array('ls', 'ls.png'),
		'Liberia'											=> array('lr', 'lr.png'),
		'Libyan Arab Jamahiriya'							=> array('ly', 'ly.png'),
		'Liechtenstein'										=> array('li', 'li.png'),
		'Lithuania'											=> array('lt', 'lt.png'),
		'Luxembourg'										=> array('lu', 'lu.png'),
		'Macao'												=> array('mo', 'mo.png'),
		'Macedonia'											=> array('mk', 'mk.png'),
		'Madagascar'										=> array('mg', 'mg.png'),
		'Malawi'											=> array('mw', 'mw.png'),
		'Malaysia'											=> array('my', 'my.png'),
		'Maldives'											=> array('mv', 'mv.png'),
		'Mali'												=> array('ml', 'ml.png'),
		'Malta'												=> array('mt', 'mt.png'),
		'Marshall Island'									=> array('mh', 'mh.png'),
		'Martinique'										=> array('mq', 'mq.png'),
		'Mauritania'										=> array('mr', 'mr.png'),
		'Mauritius'											=> array('mu', 'mu.png'),
		'Mayotte'											=> array('yt', 'yt.png'),
		'Mexico'											=> array('mx', 'mx.png'),
		'Micronesia'										=> array('fm', 'fm.png'),
		'Moldova'											=> array('md', 'md.png'),
		'Monaco'											=> array('mc', 'mc.png'),
		'Mongolia'											=> array('mn', 'mn.png'),
		'Montenegro'										=> array('me', 'me.png'),
		'Montserrat'										=> array('ms', 'ms.png'),
		'Morocco'											=> array('ma', 'ma.png'),
		'Mozambique'										=> array('mz', 'mz.png'),
		'Myanmar'											=> array('mm', 'mm.png'),
		'Namibia'											=> array('na', 'na.png'),
		'Nauru'												=> array('nr', 'nr.png'),
		'Nepal'												=> array('np', 'np.png'),
		'Netherlands'										=> array('nl', 'nl.png'),
		'Netherlands Antilles'								=> array('an', 'an.png'),
		'New Caledonia'										=> array('nc', 'nc.png'),
		'New Zealand'										=> array('nz', 'nz.png'),
		'Nicaragua'											=> array('ni', 'ni.png'),
		'Niger'												=> array('ne', 'ne.png'),
		'Nigeria'											=> array('ng', 'ng.png'),
		'Niue'												=> array('nu', 'nu.png'),
		'Norfolk Island'									=> array('nf', 'nf.png'),
		'Northern Mariana Islands'							=> array('mp', 'mp.png'),
		'Norway'											=> array('no', 'no.png'),
		'Oman'												=> array('om', 'om.png'),
		'Pakistan'											=> array('pk', 'pk.png'),
		'Palau'												=> array('pw', 'pw.png'),
		'Palestine'											=> array('ps', 'ps.png'),
		'Panama'											=> array('pa', 'pa.png'),
		'Papua New Guinea'									=> array('pg', 'pg.png'),
		'Paraguay'											=> array('py', 'py.png'),
		'Peru'												=> array('pe', 'pe.png'),
		'Philippines'										=> array('ph', 'ph.png'),
		'Pitcairn'											=> array('pn', 'pn.png'),
		'Poland'											=> array('pl', 'pl.png'),
		'Portugal'											=> array('pt', 'pt.png'),
		'Puerto Rico'										=> array('pr', 'pr.png'),
		'Qatar'												=> array('qa', 'qa.png'),
		'Reunion'											=> array('re', 're.png'),
		'Romania'											=> array('ro', 'ro.png'),
		'Russia'											=> array('ru', 'ru.png'),
		'Rwanda'											=> array('rw', 'rw.png'),
		'Saint Helena'										=> array('sh', 'sh.png'),
		'Saint Kitts and Nevis'								=> array('kn', 'kn.png'),
		'Saint Lucia'										=> array('lc', 'lc.png'),
		'Saint Pierre and Miquelon'							=> array('pm', 'pm.png'),
		'Saint Vincent and the Grenadines'					=> array('vc', 'vc.png'),
		'Samoa'												=> array('ws', 'ws.png'),
		'San Marino'										=> array('sm', 'sm.png'),
		'Sao Tome and Principe'								=> array('st', 'st.png'),
		'Saudi Arabia'										=> array('sa', 'sa.png'),
		'Senegal'											=> array('sn', 'sn.png'),
		'Serbia'											=> array('rs', 'rs.png'),
		'Seychelles'										=> array('sc', 'sc.png'),
		'Sierra Leone'										=> array('sl', 'sl.png'),
		'Singapore'											=> array('sg', 'sg.png'),
		'Slovakia'											=> array('sk', 'sk.png'),
		'Slovenia'											=> array('si', 'si.png'),
		'Slomon Islands'									=> array('sb', 'sb.png'),
		'Somalia'											=> array('so', 'so.png'),
		'South Africa'										=> array('za', 'za.png'),
		'South Georgia and the South Sandwich Islands'		=> array('gs', 'gs.png'),
		'Spain'												=> array('es', 'es.png'),
		'Sri Lanka'											=> array('lk', 'lk.png'),
		'Sudan'												=> array('sd', 'sd.png'),
		'Suriname'											=> array('sr', 'sr.png'),
		'Svalbard and Jan Mayen'							=> array('sj', 'sj.png'),
		'Swaziland'											=> array('sz', 'sz.png'),
		'Sweden'											=> array('se', 'se.png'),
		'Switzerland'										=> array('ch', 'ch.png'),
		'Syria'												=> array('sy', 'sy.png'),
		'Taiwan'											=> array('tw', 'tw.png'),
		'Tajikistan'										=> array('tj', 'tj.png'),
		'Tanzania'											=> array('tz', 'tz.png'),
		'Thailand'											=> array('th', 'th.png'),
		'Timor-Leste'										=> array('tl', 'tl.png'),
		'Togo'												=> array('tg', 'tg.png'),
		'Tokelau'											=> array('tk', 'tk.png'),
		'Tonga'												=> array('to', 'to.png'),
		'Trinidad and Tobago'								=> array('tt', 'tt.png'),
		'Tunisia'											=> array('tn', 'tn.png'),
		'Turkey'											=> array('tr', 'tr.png'),
		'Turkmenistan'										=> array('tm', 'tm.png'),
		'Turks and Caicos Islands'							=> array('tc', 'tc.png'),
		'Tuvalu'											=> array('tv', 'tv.png'),
		'Uganda'											=> array('ug', 'ug.png'),
		'Ukraine'											=> array('ua', 'ua.png'),
		'United Arab Emirates'								=> array('ae', 'ae.png'),
		'United Kingdom'									=> array('uk', 'uk.png'),
		'United States'										=> array('us', 'us.png'),
		'United States Minor Outlying Islands'				=> array('um', 'um.png'),
		'Uruguay'											=> array('uy', 'uy.png'),
		'Uzbekistan'										=> array('uz', 'uz.png'),
		'Vanuatu'											=> array('vu', 'vu.png'),
		'Venezuela'											=> array('ve', 've.png'),
		'Vietnam'											=> array('vn', 'vn.png'),
		'Virgin Islands (British)'							=> array('vg', 'vg.png'),
		'Virgin Islands (US)'								=> array('vi', 'vi.png'),
		'Wallis and Futuna'									=> array('wf', 'wf.png'),
		'Western Sahara'									=> array('eh', 'eh.png'),
		'Yemen'												=> array('ye', 'ye.png'),
		'Zambia'											=> array('zm', 'zm.png'),
		'Zimbabwe'											=> array('zw', 'zw.png'),
	);

	foreach ($flag_list as $flag_country => $flag_ary)
	{
		$sql = 'INSERT INTO ' . FLAGS_TABLE . ' ' . $db->sql_build_array('INSERT', array(
			'flag_country'		=> $flag_country,
			'flag_code'			=> $flag_ary[0],
			'flag_image'		=> $flag_ary[1],
		));

		_sql($sql, $errored, $error_ary);
	}
}

?>